<template>
  <div class="home-container">
    <!-- 头部导航栏 -->
    <van-nav-bar fixed>
      <template #left>
        <img src="@/assets/image/logo.png" class="logo"/>
      </template>
      <template #right>
        <van-icon
          name="search"
          size=".48rem"
          color="#fff"
          @click="$router.push('/search')"/>
      </template>
    </van-nav-bar>
    <!-- 频道切换 -->
    <van-tabs
      v-model="channelId"
      sticky
      animated
      offset-top="1.226666rem"
      @scroll="onScrollFn"
      >
      <van-tab
        v-for="obj in userChannelList"
        :key="obj.id"
        :title="obj.name"
        :name="obj.id"
        >
        <van-pull-refresh
          v-model="isLoading"
          @refresh="pullDownRefreshFn">
          <van-list
            v-model="loading"
            :finished="done"
            finished-text="我是有点底线的！"
            @load="pullUpLoadMoreFn"
            :immediate-check="false"
            offset="80"
            >
            <ArticleList :arr="articleList" @del-art="delArtFn"/>
          </van-list>
        </van-pull-refresh>
      </van-tab>
    </van-tabs>
    <van-icon
        name="plus"
        size="0.45rem"
        class="moreChannels"
        @click="show = true"/>
    <!-- 频道管理的弹出层 -->
    <van-popup
        v-model="show"
        class="edit_wrap"
      >
      <!-- <ChannelEdit
        :selectedChannelList="userChannelList"
        @close-popup="show = false"
        @add-channel="userChannelList.push($event)"/> -->
         <ChannelEdit
            :selectedChannelList="userChannelList"
            @close-popup="show = false"
            @add-channel="addUserChannelFn"
            @del-channel="delUserChannelFn"
            @enter-channel="enterUserChannelFn"/>
    </van-popup>
  </div>
</template>

<script>
import { getUserChannelListAPI, getArticleListAPI, updateUserChannelListAPI } from '@/api/home'
import ArticleList from './ArticleList'
import ChannelEdit from './ChannelEdit.vue'
// 存储每个频道的滚动位置的对象
const scrollMap = {}
export default {
  name: 'Home',
  components: { ArticleList, ChannelEdit },
  data () {
    return {
      userChannelList: [], // 用户选择的频道列表
      channelId: 0, // 当前激活（选中的频道），默认值是零，表示推荐频道
      articleList: [], // 当前呈现的文章列表
      loading: false, // 控制上拉每一页的加载状态
      done: false, // 控制整个上拉的加载状态
      nextTime: undefined, // 分页用的时间戳（需要把每一次后台返回的pre_timestamp保存起来）
      isLoading: false, // 控制下拉的加载状态
      show: false // 控制频道管理掏出层的可见性
    }
  },
  watch: {
    async channelId () {
      this.loading = this.done = false
      this.nextTime = undefined
      // 发请求, 替换（覆盖）旧数组articleList变量
      const resp = await getArticleListAPI({
        channelId: this.channelId
      })
      const {
        results,
        pre_timestamp: timestamp
      } = resp.data
      this.nextTime = timestamp
      this.articleList = results

      setTimeout(() => {
        console.log(scrollMap[this.channelId])
        window.scrollTo(0, scrollMap[this.channelId] || 0)
      }, 50)
    }
  },
  beforeRouteLeave (to, from, next) {
    this.scrollY = window.scrollY
    next()
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
  },
  /*
  deactivated () {
    保存滚动条的位置
    console.log('OMG', window.scrollY)
  }, */
  activated () {
    window.scrollTo(0, this.scrollY || 0)
  },
  async created () {
    let resp = await getUserChannelListAPI()
    this.userChannelList = resp.data.channels
    resp = await getArticleListAPI({
      channelId: this.channelId
    })
    const {
      results,
      pre_timestamp: timestamp
    } = resp.data
    this.nextTime = timestamp
    this.articleList = results
  },
  methods: {
    // 频道文章列表的滚动事件
    onScrollFn ({ scrollTop }) {
      scrollMap[this.channelId] = scrollTop
    },
    // 进入频道
    enterUserChannelFn (channelId) {
      this.channelId = channelId
      this.show = false
    },
    // 更新用户频道
    async updateUserChannelFn () {
      // 组装一个符合要求数组，作为参数传给接口
      // [{id: 频道id，seq: 下标 + 1}, {}]
      //  调接口
      const arr = this.userChannelList
        .reduce((sum, obj, idx) => {
          const item = {
            id: obj.id,
            seq: idx + 1
          }
          if (item.id !== 0) {
            sum.push(item)
          }
          return sum
        }, [])
      await updateUserChannelListAPI({
        channels: arr
      })
    },
    // 删除频道
    delUserChannelFn (i) {
      // 2. 同步到vue变量中
      this.userChannelList.splice(i, 1)
      // 1. 同步到后台
      this.updateUserChannelFn()
    },
    // 添加频道
    addUserChannelFn (item) {
      // 2. 同步到vue变量中
      this.userChannelList.push(item)
      // 1. 同步到后台
      this.updateUserChannelFn()
    },
    // 删除文章
    async delArtFn (i) {
      this.articleList.splice(i, 1)
      // 当数组的长度小于6时，再重新获取一次数组，防止内容漏出空白
      if (this.articleList.length < 6) {
        // 发请求(需要把让一次后台返回的pre_timestamp带过去，分页)
        const resp = await getArticleListAPI({
          channelId: this.channelId,
          timestamp: this.nextTime
        })
        const {
          results,
          pre_timestamp: timestamp
        } = resp.data
        if (timestamp === null || results.length < 10) {
          return
        }
        this.nextTime = timestamp
        // 旧、新 数组 合并 ...
        this.articleList = [
          ...this.articleList,
          ...results
        ]
      }
    },
    // 下拉刷新
    async pullDownRefreshFn () {
      const resp = await getArticleListAPI({
        channelId: this.channelId,
        timestamp: this.nextTime
      })
      const {
        results,
        pre_timestamp: timestamp
      } = resp.data
      if (timestamp === null || results.length < 10) {
        this.$toast('没了！')
        return
      }
      this.nextTime = timestamp
      // 暴力覆盖
      // this.articleList = results
      setTimeout(() => {
        // 新、旧数组合并，新的在前，旧的在后
        this.articleList = [...results, ...this.articleList]
        this.isLoading = false
      }, 1000)
    },
    // 上拉加载更多
    async pullUpLoadMoreFn () {
      // 发请求(需要把让一次后台返回的pre_timestamp带过去，分页)
      const resp = await getArticleListAPI({
        channelId: this.channelId,
        timestamp: this.nextTime
      })
      const {
        results,
        pre_timestamp: timestamp
      } = resp.data
      if (timestamp === null || results.length < 10) {
        this.done = true
        return
      }
      this.nextTime = timestamp
      // 旧、新 数组 合并 ...
      this.articleList = [
        ...this.articleList,
        ...results
      ]
      // 可以继续后续的请求了
      this.loading = false
    }
  }
}
</script>

<style lang="less" scoped>
.logo {
  width: 100px;
  height: 30px;
}
/* tab内容距离tab导航的距离 */
/deep/ .van-tabs__content{
  padding-top: 44px;
}
// 设置 tabs 容器的样式
/deep/ .van-tabs__wrap {
  padding-right: 20px;
  background-color: #fff;
}
// 设置小图标的样式
.moreChannels {
  position: fixed;
  top: 60px;
  right: 8px;
  z-index: 999;
}
/* 频道编辑弹出层铺满屏幕 */
.edit_wrap{
  width: 100%;
  height: 100%;
}
</style>
